/**
 *  处理数据格式
 * */
import {$each, $isEmptyArr, $isEmptyObject, isArray, isNullOrEmpty, isNumber} from "./index";

// 数据格式的特殊情况
const dealDataFormatStrategy = {
  chart_scatter_simple(data, rulesOption) {
    data.value.forEach((value, index) => {
      // 散点图比较特殊，第三个值是维度，所以不需要处理第三个值
      if (index !== 2) {
        data.value[index] = Number(value && value.toFixed(rulesOption.numberDigit));
      }
    });
  },
  chart_scatter_basic(data, rulesOption) {
    data.value.forEach((value, index) => {
      // 气泡图比较特殊，第三个值是气泡大小，第四个是维度，所以不需要处理第三个后的值
      if (index < 3) {
        data.value[index] = Number(value && value.toFixed(rulesOption.numberDigit));
      }
    });
  },
  chart_scatter_punch(data, rules,dimensions) {
    data.value.forEach((value, index) => {
      // 打卡-气泡图比较特殊，只需处理第三个值是气泡大小
      if (index === 2) {
        data.value[index] = Number(value && value.toFixed(rules[`${dimensions.yAxisSize}New`]?.numberDigit));
      }
    });
  },
  map_scatter(data, rules, dimensions) {
    const { dataFormatType } = data;

    const { numberDigit } = rules [`${dimensions[dataFormatType]}New`] || {
      numberDigit: null
    };
    //气泡大小度量
    if (dataFormatType === 'yAxis' && data.value) {
      // 等于yAxis的时候，是气泡大小/度量，有三个值，前两个是经纬度，不需要转换
      const index = data.value.length - 1;
      data.value[index] = handleFixed(data.value[index], numberDigit);
      $each(data.tooltip, (item, key) => {
        data.tooltip[key] = handleFixed(item, rules[`${key}New`]?.numberDigit || null);
      })
    }else {
      //地图颜色度量
      data.value = handleFixed(data.value, numberDigit);
    }
  },
  all(data, rulesOption) {
    data.value.forEach((value, index) => {
      data.value[index] = value && Number(value.toFixed(rulesOption.numberDigit));
    });
  },
  map_flyingLine(data, rules, dimensions, dataFormatType, dataSets) {
    if(isNullOrEmpty (dataFormatType)) {
      return ;
    }
    const { type } = dataSets;
    //飞线地图只需要处理飞线度量
    if(dataFormatType === 'yAxis') {
      const { linesValue = [] } = data;
      linesValue.forEach((item) => {
        const name = type !== 'STATIC' ? item.name : dimensions[dataFormatType];
        item.value = item.value && Number(item.value.toFixed(rules[`${name}New`]?.numberDigit));
      });
    }else {
      //地图颜色度量
      data.value = handleFixed(data.value, rules[`${dimensions[dataFormatType]}New`]?.numberDigit);
    }

  },
  // 散点特殊数据格式的处理
  specialScatter(data, rules,dimensions) {
    if($isEmptyArr(data.value)) {
      return;
    }
    //X轴度量
    data.value[0] = handleFixed(data.value[0], rules[`${dimensions.xAxisScatter}New`]?.numberDigit );
    //y轴度量
    data.value[1] = handleFixed(data.value[1], rules[`${dimensions.yAxis}New`]?.numberDigit);
  },
  //有分子分母数据格式的处理
  stripProgress(data, rulesOption) {
    let { tooltip } = data;
    Object.values(tooltip).map(item => {
      item.value = handleFixed(item.value, rulesOption.numberDigit)
    })
    const { yAxis, yAxisBar } = tooltip;
    data.value = yAxis.value && yAxisBar.value ? Number(Number(((yAxis.value / yAxisBar.value) * 100).toFixed(2))) : 0;

  }
};

function handleFixed(value, numberDigit) {
  return value ? !isNullOrEmpty(numberDigit) ? Number(Number(value).toFixed(numberDigit)) : value : 0;
}
//有分子分母的组件
const stripComponents = ['chart_strip_progress1', 'chart_strip_percent', 'chart_strip_progress2', 'chart_strip_progress3', 'chart_bar_percent']
// 有x轴度量，y轴度量及气泡大小的组件
const scatterComponents = ['chart_scatter_basic', 'chart_scatter_simple'];
//其他组件
const otherComponents  = ['map_scatter', 'chart_scatter_punch','map_flyingLine'];

export function handleDealDataFormat(dataSets, rules, componentKey) {
  if (!rules || $isEmptyObject(rules)) {
    return dataSets;
  }
  const reg = /^(0|[1-9][0-9]*)$/;
  if (dataSets.seriesData) {
    $each(dataSets.seriesData, (series) => {
      $each(series.data, (item) => {
        if (item) {
          let name = '';
          name = componentKey ==='chart_pie_double' ? item.name : series.name;
          if (componentKey === 'map_flyingLine' && dataSets.type === 'STATIC' || dataSets.type !== 'STATIC' && dataSets.dimensions?.legend) {
            name = dataSets.dimensions[series.dataFormatType] || name;
          }

          const rulesOption = rules[`${name}New`] || rules[`${series.dataFormatType}New`] || rules['yAxisNew'] || {
            name: '',
            numberDigit: null,
            unit: ""
          };
          // const rulesOption = rules.options[series.dataFormatType || 'yAxis'];
          if(stripComponents.includes(componentKey)) {
            dealDataFormatStrategy.stripProgress(item, rulesOption);
          }else if(scatterComponents.includes(componentKey)) {
            dealDataFormatStrategy.specialScatter(item, rules, dataSets.dimensions);
          } else if(otherComponents.includes(componentKey)  ) {
            dealDataFormatStrategy[componentKey](item, rules, dataSets.dimensions, series.dataFormatType, dataSets);
          }else if (rulesOption && reg.test(rulesOption.numberDigit)) {
            // 格式化值,雷达图的value为数组
            if (isArray(item.value)) {
              if (dealDataFormatStrategy[componentKey]) {
                dealDataFormatStrategy[componentKey](item, rulesOption, series.dataFormatType);
              } else {
                dealDataFormatStrategy.all(item, rulesOption);
              }
            } else if (item.linesValue) {
              dealDataFormatStrategy.map_flyingLine(item, rulesOption, dataSets.dimensions, series.dataFormatType);
            } else if (item.value && isNumber(item.value)) {
              item.value = Number(item.value.toFixed(rulesOption.numberDigit));
            }
          }
        }
      });
    });
  }
  if (dataSets.formatData) {
    $each(dataSets.formatData, (item) => {
      if (item.value && isNumber(item.value)) {
        let rule = rules[`${item.name}New` || 'yAxis'];
        if (componentKey === 'info_text') {
          rule = rules[`${dataSets.dimensions['xAxis']}New`];
        }
        if (rule && reg.test(rule.numberDigit)) {
          item.value = Number(item.value.toFixed(rule.numberDigit));
        }
        // 指标卡不需要后缀
        if (rule && rule.unit && componentKey !== 'info_indicatorCard') {
          item.value = item.value + rule.unit;
        }
      }
    });
  }
  return dataSets;
}

// 数据格式列处理
const doubleKeys = {
  bi_double_line_bar: {
    fieldKeys: ['yAxis', 'yAxisLine'],
  },
  bi_line_Bar: {
    fieldKeys: ['yAxis', 'yAxisLine'],
  },
  map_scatter: {
    fieldKeys: ['yAxis', 'yAxisAreaColor'],
  },
  map_flyingLine: {
    fieldKeys: ['yAxis', 'yAxisAreaColor'],
  },
  chart_scatter_punch: {
    fieldKeys: ['yAxisSize'],
  },
  chart_scatter_basic: {
    fieldKeys: ['xAxisScatter', 'yAxis', 'yAxisSize'],
  },
  chart_scatter_simple: {
    fieldKeys: ['xAxisScatter', 'yAxis'],
  },
  chart_strip_progress2: {
    fieldKeys: ['yAxis', 'yAxisBar'],
  },
  chart_strip_percent: {
    fieldKeys: ['yAxis', 'yAxisBar'],
  },
  chart_strip_progress3: {
    fieldKeys: ['yAxis', 'yAxisBar'],
  },
  chart_strip_progress1: {
    fieldKeys: ['yAxis', 'yAxisBar'],
  },
  chart_bar_percent: {
    fieldKeys: ['yAxis', 'yAxisBar'],
  },
  chart_bar_double: {
    fieldKeys: ['yAxis', 'yAxisBar'],
  },
  bi_forecast_basic_bar: {
    fieldKeys: ['yAxisRealBar', 'yAxisEmptyBar'],
  },
  bi_forecast_basic_line: {
    fieldKeys: ['yAxisRealLine', 'yAxisEmptyLine'],
  },
  bi_forecast_basic_bar_line: {
    fieldKeys: ['yAxisRealBar', 'yAxisEmptyBar', 'yAxisRealLine', 'yAxisEmptyLine'],
  },
  bi_forecast_bouble_y_basic_bar_line: {
    fieldKeys: ['yAxisRealBar', 'yAxisEmptyBar', 'yAxisRealLine', 'yAxisEmptyLine'],
  },
};

export function handleColumnSelectData(componentKey, fields) {
  const options = [];
  if (!componentKey) {
    return options;
  }
  if (doubleKeys[componentKey]) {
    const keys = doubleKeys[componentKey].fieldKeys;
    $each(fields, (item, key) => {
      if (keys.includes(key)) {
        options.push({
          key: item.name,
          value: item.key,
        });
      }
    });
  } else {
    options.push({
      key: '度量',
      value: 'yAxis',
    });
  }
  return options;
}

export function generateComponentFieldFormatMap(block) {
  const { relationData = undefined, props } = block;
  const rules = {};
  if (!isNullOrEmpty(relationData)) {
    if (props?.dataFormat?.value) {
      const { options = {} } = props.dataFormat.value;
      Object.keys(options).forEach((key) => {
        rules[key] = options[key].unitSuffix;
        relationData.fields[key]?.relations.map((relation) => {
          const dataformat = relation.dataFormat;
          if (dataformat) {
            rules[relation.alias || relation.columnAlias || relation.columnName] = options[key].unitSuffix;
          }
        });
      });
    }
    // 新版字段映射覆盖旧版的设置
    const selectOptions = handleColumnSelectData(block.componentKey, relationData.fields);

    selectOptions.map((item) => {
      // 对遗弃的样式设置的props.dataFormat进行具体度量值的格式化赋值
      const itemValue =
        block.componentKey === 'info_text' && item.value === 'yAxis' ? 'xAxis' : item.value;
      relationData.fields[itemValue]?.relations.map((relation) => {
        const dataformat = relation.dataFormat;
        if (dataformat) {
          rules[relation.alias || relation.columnAlias || relation.columnName] = dataformat.unit;
          rules[`${relation.alias || relation.columnAlias|| relation.columnName}New`] = dataformat;
        }
      });
    });

    // 静态数据映射
    const staticDataFormat = relationData.dcConfig?.staticDataFormat;
    if (staticDataFormat) {
      Object.keys(staticDataFormat).map((key) => {
        rules[`${key}New`] = staticDataFormat[key];
        rules[`${key}`] = staticDataFormat[key].unit;
      });
    }
    return rules;
  }
}
